package com.hndzyu.yd.home;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Outline;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.bean.Discount;
import com.hndzyu.yd.bean.VIPDiscount;
import com.hndzyu.yd.vip.PDDFragment;
import com.hndzyu.yd.widget.RoundAngleImageView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.hndzyu.yd.R;
import com.hndzyu.yd.base.BaseApplication;
import com.hndzyu.yd.bean.APP2;
import com.hndzyu.yd.bean.App;
import com.hndzyu.yd.bean.CustomObject;
import com.hndzyu.yd.bean.GameList;
import com.hndzyu.yd.bean.Home;
import com.hndzyu.yd.bean.PDD;
import com.hndzyu.yd.bean.RandomCard;
import com.hndzyu.yd.bean.RandomFollow;
import com.hndzyu.yd.bean.RandomShare;
import com.hndzyu.yd.bean.Share;
import com.hndzyu.yd.bean.TX;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.bean.UserLM;
import com.hndzyu.yd.bean.Wechat;
import com.hndzyu.yd.bean.XW;
import com.hndzyu.yd.customtask.CreditCardDetailsActivity;
import com.hndzyu.yd.customtask.CreditTaskDetailsActivity;
import com.hndzyu.yd.customtask.ScreenAdapter;
import com.hndzyu.yd.customtask.ScreenBean;
import com.hndzyu.yd.my.TiXianActivity;
import com.hndzyu.yd.task.FollowActivity;
import com.hndzyu.yd.task.FollowAdapter;
import com.hndzyu.yd.task.ShareAdapter;
import com.hndzyu.yd.task.WebActivity;
import com.hndzyu.yd.ui.BindingPhoneActivity;
import com.hndzyu.yd.ui.LoginActivity;
import com.hndzyu.yd.ui.NewActivity;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.SharedPreferencesUtils;
import com.hndzyu.yd.utils.Util;
import com.hndzyu.yd.vip.GameActivity;
import com.hndzyu.yd.vip.GameDetailActivity;
import com.hndzyu.yd.vip.PDDActivity;
import com.hndzyu.yd.vip.PDDAdapter;
import com.hndzyu.yd.vip.PDDDetailActivity;
import com.hndzyu.yd.vip.XWActivity;
import com.hndzyu.yd.widget.BindDialog;
import com.hndzyu.yd.widget.JDAdverView;
import com.hndzyu.yd.widget.JDViewAdapter;
import com.hndzyu.yd.widget.MakeMoneyDialog;
import com.hndzyu.yd.widget.MyListView;
import com.hndzyu.yd.widget.SignDialog;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import xcs.ert.jlj.os.df.AdExtraTaskStatus;
import xcs.ert.jlj.os.df.AppExtraTaskObject;
import xcs.ert.jlj.os.df.AppExtraTaskObjectList;
import xcs.ert.jlj.os.df.AppSummaryDataInterface;
import xcs.ert.jlj.os.df.AppSummaryObject;
import xcs.ert.jlj.os.df.AppSummaryObjectList;
import xcs.ert.jlj.os.df.DiyOfferWallManager;

/**
 * Created by zz9527 on 2018/10/11.
 */
public class HomeFragment extends Fragment implements View.OnClickListener {
    private GVAdapter gvAdapter;
    private GridView gv;
    private ListView tj;
    private TJAdapter tjAdapter;
    private SmartRefreshLayout refresh;
    private ArrayList<CustomObject> tjcustomObjectArrayList;
    private ArrayList<CustomObject> zxcustomObjectArrayList = new ArrayList<CustomObject>();
    private JDAdverView jd;
    private TextView dangqian;
    private ImmersionBar mImmersionBar;
    private View start;
    private TagFlowLayout flow;
    private LinearLayout lltj;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initImmersionBar();
        initView(view);
//        getData();
        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.DISCOUNT(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {

                try {
                    Gson gson = new Gson();
                    Discount.DataBean bean = gson.fromJson(json, Discount.class).getData();
                    if (bean.getIsshow()!=1) {
                    } else {
                            final MakeMoneyDialog makeDIalog = new MakeMoneyDialog(getContext());
                            makeDIalog.setListener(new MakeMoneyDialog.MakeMoneyListener() {
                                @Override
                                public void checktrue() {
                                    makeDIalog.dismiss();
                                }
                            });
                            makeDIalog.show();
                            makeDIalog.setImg(Path.img(bean.getBanner()));
                        }

                } catch (Exception e) {

                }
            }

        });
        getApp();
        getHome();
        money(UserBean.uid);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            if (onButtonClick != null) {
                onButtonClick.onClick(1, 1);
                BaseApplication.starShare = true;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initView(View view) {
        ImageView vip = view.findViewById(R.id.home_vip);
        jd = view.findViewById(R.id.jd);
        gv = view.findViewById(R.id.home_zuixin);
        tj = view.findViewById(R.id.home_tuijian);
        lltj = view.findViewById(R.id.ll_tj);
        Banner banner = view.findViewById(R.id.banner);
        Integer[] images = {R.mipmap.random, R.mipmap.banner_2, R.mipmap.banner_3};
        List<Integer> resultList = new ArrayList<>(images.length);
        for (Integer s : images) {
            resultList.add(s);
        }
        banner.setImages(resultList).setImageLoader(new GlideImageLoader()).start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (position == 0) {
                    RandomTask();
                }
            }
        });
        view.setClipToOutline(true);
        gv.setFocusable(false);
        tj.setFocusable(false);
        jd.setFocusable(false);

        view.findViewById(R.id.home_more_share).setOnClickListener(this);
        view.findViewById(R.id.home_more_follow).setOnClickListener(this);
        view.findViewById(R.id.home_more_gw).setOnClickListener(this);
        view.findViewById(R.id.home_more_taskmore).setOnClickListener(this);
        final TextView more1 = view.findViewById(R.id.home_more);
        final TextView more2 = view.findViewById(R.id.home_more2);
        more1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onButtonClick != null) {
                    onButtonClick.onClick(1, 0);
                }
            }
        });
        more2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onButtonClick != null) {
                    onButtonClick.onClick(1, 0);
                }

            }
        });
        view.findViewById(R.id.xuanfu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(mcontext, NewActivity.class), 1);
            }
        });
        if (UserBean.level > 0) {
            vip.setVisibility(View.VISIBLE);
            vip.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onButtonClick.onClick(4, 0);
                }
            });
        }
        dangqian = view.findViewById(R.id.dangqianyuer);
        view.findViewById(R.id.tixianarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserBean.uid != 0) {
                    if ("".equals(UserBean.mobile)) {
                        final BindDialog bindDIalog = new BindDialog(mcontext);
                        bindDIalog.setBindListener(new BindDialog.BindListener() {
                            @Override
                            public void chooseTrue() {
                                startActivity(new Intent(getActivity(), BindingPhoneActivity.class));
                                bindDIalog.dismiss();
                            }

                            @Override
                            public void chooseFalse() {
                                bindDIalog.dismiss();

                            }
                        });
                        bindDIalog.show();
                        bindDIalog.setContent();

                    } else {
                        startActivity(new Intent(getActivity(), TiXianActivity.class));
                    }

                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
            }
        });
        refresh = view.findViewById(R.id.refresh);
        //设置 Header 样式
        refresh.setRefreshHeader(new MaterialHeader(mcontext));
//        //设置 Footer 样式
//        refresh.setRefreshFooter(new ClassicsFooter(mcontext));
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                jd.stop();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                zxcustomObjectArrayList.clear();
                getApp();
            }
        });
//        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(RefreshLayout refreshlayout) {
//                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
//            }
//        });
        //签到
        final SignDialog dialog = new SignDialog(getActivity());

        view.findViewById(R.id.ll_home_qiandao).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserBean.uid == 0) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.QD(UserBean.uid + ""), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                        @Override
                        public void onsendJson(String json) {
                            try {
                                JSONObject object = new JSONObject(json);
                                if (object.optString("info").contains("成功")) {
                                    dialog.setListener(new SignDialog.SignListener() {
                                        @Override
                                        public void checktrue() {
                                            dialog.dismiss();
                                        }
                                    });
                                    dialog.show();
                                    dialog.showMsg("签到成功");
                                    money(UserBean.uid);
                                } else {
                                    dialog.setListener(new SignDialog.SignListener() {
                                        @Override
                                        public void checktrue() {
                                            dialog.dismiss();
                                        }
                                    });
                                    dialog.show();
                                    dialog.showMsg("今日已签到");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
        view.findViewById(R.id.ll_home_yaoqinghaoyou).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserBean.uid == 0) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), InvitationActivity.class));
                }
            }
        });
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                if (zxcustomObjectArrayList.get(i).getAppSummaryObject().getAppName().contains("#")) {
                    intent.setClass(getActivity(), AppDetailActivity.class);
                    intent.putExtra("app", zxcustomObjectArrayList.get(i).getAppSummaryObject().getAppName());
                } else {
                    intent.setClass(getActivity(), TaskDetailActivity.class);
                    intent.putExtra("ad", zxcustomObjectArrayList.get(i).getAppSummaryObject());
                }
                startActivity(intent);
            }
        });
        tj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), TaskDetailActivity.class);
                intent.putExtra("ad", tjcustomObjectArrayList.get(i).getAppSummaryObject());
                startActivity(intent);
            }
        });

        lvshare = view.findViewById(R.id.home_share);
        lvfollow = view.findViewById(R.id.home_follow);
        lvgw = view.findViewById(R.id.home_gw);
        lvshare.setFocusable(false);
        lvfollow.setFocusable(false);
        lvgw.setFocusable(false);
        ;
        lvtaskmore = view.findViewById(R.id.home_taskmore);
        ImageView iv = view.findViewById(R.id.home_game);
        Glide.with(this).load(R.mipmap.home_game_gif).into(iv);
        iv.setOnClickListener(this);
        lvtaskmore.setLayoutManager(new LinearLayoutManager(mcontext));
    }

    private MyListView lvshare;
    private MyListView lvfollow;
    private MyListView lvgw;
    private RecyclerView lvtaskmore;

    private void getApp() {
        OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.APP(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Gson gson = new Gson();
                    List<App.DataBean> data = gson.fromJson(json, App.class).getData();
                    for (int k = 0; k < data.size(); ++k) {
                        if (zxcustomObjectArrayList.size() == 4) {
                            return;
                        }
                        if (data.get(k).getProtype() == 0) {
                            CustomObject customObject = new CustomObject();
                            APP2 appSummaryObject = new APP2();
                            if (data.get(k).getProtasktype() == 0) {
                                appSummaryObject.setAppName(data.get(k).getProname() + "#" + data.get(k).getProid() + "#" + data.get(k).getBaoname() + "#" + data.get(k).getDaninstall());
                            } else {
                                appSummaryObject.setAppName(data.get(k).getProname() + "#" + data.get(k).getProid() + "#" + data.get(k).getBaoname() + "#" + data.get(k).getTotalamount());
                            }
                            appSummaryObject.setPoints((int) (Double.parseDouble(data.get(k).getTotalamount() + "")));
                            customObject.setAppSummaryObject(appSummaryObject);
                            customObject.setAppicon(data.get(k).getAppicon());
                            zxcustomObjectArrayList.add(customObject);
                        }
                    }
                    getData();
                } else {
                    if (mcontext != null) {
                        Toast.makeText(mcontext, "网络异常", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void getData() {
        // 获取指定类型 的广告，并更新listview，下面展示两种加载方式，开发者可选择适合自己的方式
        // 异步加载方式
        // 请求类型，页码，请求数量，回调接口
        DiyOfferWallManager.getInstance(mcontext)
                .loadOfferWallAdList(1, 1, 15, new AppSummaryDataInterface() {


                    /**
                     * 当成功获取到积分墙列表数据的时候，会回调这个方法（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     * 注意：列表数据有可能为空（比如：没有广告的时候），开发者处理之前，请先判断列表是否为空，大小是否大与0
                     */
                    @Override
                    public void onLoadAppSumDataSuccess(Context context, final AppSummaryObjectList adList) {
                        if (adList == null || adList.isEmpty()) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    mSwipeRefreshLayout.setRefreshing(false);
//                                    mSwipeRefreshLayout.setPushRefreshFinish();
                                    Toast.makeText(mcontext, "没有获取到更多的任务，晚点在来吧~", Toast.LENGTH_LONG).show();
                                }
                            });
                        } else {
                            if (adList == null || adList.isEmpty()) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        mSwipeRefreshLayout.setRefreshing(false);
//                                        mSwipeRefreshLayout.setPushRefreshFinish();
                                        Toast.makeText(mcontext, "没有获取到更多的任务，晚点在来吧~", Toast.LENGTH_LONG).show();
                                    }
                                });
                            } else {
                                if (zxcustomObjectArrayList.size() < 4) {
                                    int size = 4 - zxcustomObjectArrayList.size();
                                    for (int k = 0; k < size; k++) {
                                        CustomObject customObject = new CustomObject();
                                        customObject.setAppSummaryObject(adList.get(k));
                                        customObject.setAppicon(adList.get(k).getIconUrl());
                                        zxcustomObjectArrayList.add(customObject);
                                    }
                                }
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        gvAdapter = new GVAdapter(zxcustomObjectArrayList, mcontext, 1);
                                        gv.setAdapter(gvAdapter);

//                                        Toast.makeText(mcontext,
//                                                String.format("请求成功\n请求页码：%s\n请求数量：%s\n实际返回数量:%s\n当天新任务限制:%s\n已安装的新任务数:%s", adList.getPageIndex(),
//                                                        adList.getPerPageNumber(), adList.size(), adList.getInstallLimit(), adList.getInstallTimes
//                                                                ()),
//                                                Toast.LENGTH_LONG).show();
                                    }
                                });
                                tjcustomObjectArrayList = new ArrayList<CustomObject>();
                                for (int k = 4; k < adList.size(); ++k) {
                                    CustomObject customObject = new CustomObject();
                                    customObject.setAppSummaryObject(adList.get(k));
                                    customObject.setAppicon(adList.get(k).getIconUrl());
                                    tjcustomObjectArrayList.add(customObject);
                                }
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tjAdapter = new TJAdapter(tjcustomObjectArrayList, mcontext);
                                        tj.setAdapter(tjAdapter);

//                                        Toast.makeText(mcontext,
//                                                String.format("请求成功\n请求页码：%s\n请求数量：%s\n实际返回数量:%s\n当天新任务限制:%s\n已安装的新任务数:%s", adList.getPageIndex(),
//                                                        adList.getPerPageNumber(), adList.size(), adList.getInstallLimit(), adList.getInstallTimes
//                                                                ()),
//                                                Toast.LENGTH_LONG).show();
                                    }
                                });

                            }
                            if (adList != null) {
                                updateLimitInfo(adList.getInstallLimit(), adList.getInstallTimes());
                            }
                        }
                    }

                    /**
                     * 因为网络问题而导致请求失败时，会回调这个接口（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     */
                    @Override
                    public void onLoadAppSumDataFailed() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

//                                mSwipeRefreshLayout.setRefreshing(false);
//                                mSwipeRefreshLayout.setPushRefreshFinish();
//                                Toast.makeText(mcontext, "请求失败，请检查网络～", Toast.LENGTH_LONG).show();
                                gvAdapter = new GVAdapter(zxcustomObjectArrayList, mcontext, 1);
                                gv.setAdapter(gvAdapter);
                                tj.setVisibility(View.GONE);
                                lltj.setVisibility(View.GONE);
                            }
                        });
                    }

                    /**
                     * 请求成功，但是返回有米错误代码时候，会回调这个接口（注意:本接口不在UI线程中执行， 所以请不要在本接口中进行UI线程方面的操作）
                     */
                    @Override
                    public void onLoadAppSumDataFailedWithErrorCode(final int code) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                mSwipeRefreshLayout.setRefreshing(false);
//                                mSwipeRefreshLayout.setPushRefreshFinish();
//                                Toast.makeText(mcontext, String.format("请求错误，错误代码 ： %d， 请联系客服", code),
//                                        Toast.LENGTH_LONG).show();
                                gvAdapter = new GVAdapter(zxcustomObjectArrayList, mcontext, 1);
                                gv.setAdapter(gvAdapter);
                                tj.setVisibility(View.GONE);
                                lltj.setVisibility(View.GONE);
                            }
                        });
                    }
                });
        getTX();
    }

    private void getTX() {
        OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.TX(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        Gson gson = new Gson();
                        List<TX.DataBean> list = gson.fromJson(json, TX.class).getData();
                        if (list.size() >= 3) {
                            jd.setAdapter(new JDViewAdapter(Glide.with(mcontext), list));
                            jd.start();
                        }
                    } catch (Exception e) {
                    }
                } else {
                    Toast.makeText(mcontext, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void money(int uid) {
        OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.money + "?uid=" + uid, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        Gson gson = new Gson();
                        UserLM userLM = gson.fromJson(json, UserLM.class);
                        UserBean.balance = userLM.getInfo().getBalance();
                        UserBean.gao = userLM.getInfo().getGaotype();
                        UserBean.level = userLM.getInfo().getLevel();
                        UserBean.kefu = userLM.getKefu().getServicewx();

                        if (UserBean.uid != 0) {
                            SharedPreferencesUtils.setParam(mcontext, "level", UserBean.level);
                            SharedPreferencesUtils.setParam(mcontext, "gao", UserBean.gao);
                            SharedPreferencesUtils.setParam(mcontext, "balance", UserBean.balance);
                            dangqian.setText(UserBean.balance);
                        }
                    } catch (Exception e) {

                    }

                }
            }
        });
    }


    /**
     * 更新listview
     *
     * @param adList
     */
    private void updateListView(final AppSummaryObjectList adList) {

    }


    /**
     * 更新用户当前可做的任务数
     * <p/>
     * 计算当前还可以做多少个处于《未完成状态》广告：安装上限-今天已经安装过的数量
     *
     * @param installLimit 当天新任务安装限制
     * @param installTimes 当天已经完成的新任务数量
     */
    private void updateLimitInfo(final int installLimit, final int installTimes) {
//        getActivity().runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                StringBuilder sb = new StringBuilder();
//                sb.append("可做任务数：");
//                sb.append(installLimit - installTimes);
//                updateLimitInfo(sb.toString());
//            }
//        });
    }


    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
        mImmersionBar.statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (UserBean.uid != 0) {
            money(UserBean.uid);
        }
        if (!hidden && mImmersionBar != null)
            ImmersionBar.with(this)
                    .statusBarDarkFont(true, 0.2f)
                    .init();
    }

    private OnButtonClick onButtonClick;//2、定义接口成员变量

    //定义接口变量的get方法
    public OnButtonClick getOnButtonClick() {
        return onButtonClick;
    }

    //定义接口变量的set方法
    public void setOnButtonClick(OnButtonClick onButtonClick) {
        this.onButtonClick = onButtonClick;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home_more_gw:
                startActivity(new Intent(mcontext, PDDActivity.class));
                break;
            case R.id.home_more_share:
                if (onButtonClick != null) {
                    onButtonClick.onClick(1, 1);
                }
                break;
            case R.id.home_more_follow:
                if (onButtonClick != null) {
                    onButtonClick.onClick(1, 2);
                }
                break;
            case R.id.home_more_taskmore:
                if (onButtonClick != null) {
                    onButtonClick.onClick(1, 1);
                }
                break;
            case R.id.home_game:
                startActivity(new Intent(mcontext, GameActivity.class));
                break;
            default:
                break;
        }
    }

    //1、定义接口
    public interface OnButtonClick {
        public void onClick(int i, int tab);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserBean.uid != 0) {
            money(UserBean.uid);
        }
    }

    ImageView img;
    TextView title;
    TextView price;
    Dialog dialog;

    private void RandomTask() {
        int i = new Random().nextInt(4);
        final int position = new Random().nextInt(9);
        dialog = new Dialog(mcontext);
        dialog.setContentView(R.layout.dialog_randomtask);
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        lp.gravity = Gravity.CENTER;
        lp.dimAmount = 0.5f;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        img = dialog.findViewById(R.id.random_img);
        title = dialog.findViewById(R.id.random_title);
        price = dialog.findViewById(R.id.random_price);
        flow = dialog.findViewById(R.id.flowlayout);
        dialog.findViewById(R.id.huan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = new Random().nextInt(4);
                final int position = new Random().nextInt(9);
                randomSwitch(i, position);
            }
        });
        start = dialog.findViewById(R.id.start);
        randomSwitch(i, position);
    }

    private void randomSwitch(final int i, final int position) {
        switch (i) {
            case 0:
                //有米
                try {
                    Glide.with(mcontext).load(tjcustomObjectArrayList.get(position).getAppSummaryObject().getIconUrl()).into(img);
                    title.setText(tjcustomObjectArrayList.get(position).getAppSummaryObject().getAppName());
                    price.setText("+" + Util.Sub((double) getTotalPoints(tjcustomObjectArrayList.get(position).getAppSummaryObject()) * Double.parseDouble(UserBean.divide) / 100 + "") + "元");
                    ArrayList<String> strings = new ArrayList<>();
                    strings.add(tjcustomObjectArrayList.get(position).getAppSummaryObject().getAdSlogan());
                    flow.setAdapter(new TagAdapter<String>(strings) {
                        @Override
                        public View getView(FlowLayout parent, int position, String s) {
                            TextView tv = (TextView) LayoutInflater.from(mcontext).inflate(R.layout.tv,
                                    flow, false);
                            tv.setText(s);
                            return tv;
                        }
                    });
                    start.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            Intent intent = new Intent(getActivity(), TaskDetailActivity.class);
                            intent.putExtra("ad", tjcustomObjectArrayList.get(position).getAppSummaryObject());
                            startActivity(intent);
                        }
                    });
                } catch (Exception e) {
                    Toast.makeText(mcontext, "数据异常", Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                //91
                String str = Util.getIMEI(mcontext) + "#" + UserBean.uid + "#128#c938dc75fc803b68912884b0c61cdf66";
                String base = Base64.encodeToString(str.getBytes(), Base64.NO_WRAP).trim();
                final String encode = encode(base);
                OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.GAMELIST(Util.getIMEI(mcontext), UserBean.uid, encode, 1), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

                    @Override
                    public void onsendJson(String json) {
                        try {
                            Gson gson = new Gson();
                            final List<GameList.DataBean.ListBean> mlist = gson.fromJson(json, GameList.class).getData().getList();

                            title.setText(mlist.get(position).getAppName());
                            if (UserBean.level > 0) {
                                price.setText("+" + Util.Sub(Double.parseDouble(mlist.get(position).getGoldSum()) * 0.9 * (Double.parseDouble(UserBean.vipdivide) + Double.parseDouble(UserBean.divide)) + "") + "元");
                            } else {
                                price.setText("+" + Util.Sub(Double.parseDouble(mlist.get(position).getGoldSum()) * 0.9 * Double.parseDouble(UserBean.divide) + "") + "元");
                            }
                            Glide.with(mcontext).load(mlist.get(position).getLogo()).into(img);
                            flow.setAdapter(new TagAdapter<String>(mlist.get(position).getLabel()) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mcontext).inflate(R.layout.tv,
                                            flow, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            });
                            start.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    Intent intent = new Intent(mcontext, GameDetailActivity.class);
                                    intent.putExtra("sign", encode);
                                    intent.putExtra("idtask", mlist.get(position).getIDTask());
                                    startActivity(intent);

                                }
                            });

//
                        } catch (Exception e) {
                        }
                    }
                });
                break;
            case 2:
                //闲玩
                OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.GAMEXW(Util.getIMEI(mcontext), UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        try {
                            Gson gson = new Gson();
                            json = URLDecoder.decode(json, "UTF-8");
                            final List<XW.ItemsBean> list = gson.fromJson(json, XW.class).getItems();

                            title.setText(list.get(position).getAdname());
                            String showmoney = list.get(position).getShowmoney();
                            showmoney = showmoney.replace("元", "");
                            if (UserBean.level > 0) {
                                price.setText("+" + Util.Sub(Double.parseDouble(showmoney) * 2 * (Double.parseDouble(UserBean.vipdivide) + Double.parseDouble(UserBean.divide)) + "") + "元");

                            } else {
                                price.setText("+" + Util.Sub(Double.parseDouble(showmoney) * 2 * Double.parseDouble(UserBean.divide) + "") + "元");

                            }
                            Glide.with(mcontext).load(list.get(position).getImgurl()).into(img);
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add(list.get(position).getIntro());
                            flow.setAdapter(new TagAdapter<String>(strings) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mcontext).inflate(R.layout.tv,
                                            flow, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            });
                            start.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    Intent intent = new Intent(mcontext, XWActivity.class);
                                    intent.putExtra("adid", list.get(position).getAdid());
                                    startActivity(intent);

                                }
                            });
                        } catch (Exception e) {
                        }
                    }
                });
                break;
            case 3:
                OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.RandomTask(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        Gson gson = new Gson();
                        if (json.contains("shid")) {
                            final RandomShare randomShare = gson.fromJson(json, RandomShare.class);
                            Glide.with(mcontext).load(Path.img(randomShare.getData().getImg())).into(img);
                            title.setText(randomShare.getData().getShname());
                            price.setText("+" + randomShare.getData().getAll() + "元");
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add("微信分享");
                            flow.setAdapter(new TagAdapter<String>(strings) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mcontext).inflate(R.layout.tv,
                                            flow, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            });
                            start.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    Intent intent = new Intent(getActivity(), WebActivity.class);
                                    intent.putExtra("url", randomShare.getData().getUrl());
                                    intent.putExtra("shid", randomShare.getData().getShid());
                                    intent.putExtra("fen", randomShare.getData().getFen());
                                    intent.putExtra("title", randomShare.getData().getShname());
                                    intent.putExtra("img", randomShare.getData().getImg());
                                    intent.putExtra("type", randomShare.getData().getType());
                                    intent.putExtra("intro", randomShare.getData().getShcon());
                                    intent.putExtra("isshow", randomShare.getData().getIsshow());
                                    intent.putExtra("scon", randomShare.getData().getShowtext());
                                    intent.putExtra("ym", randomShare.getData().getYuming());
                                    getActivity().startActivity(intent);
                                }
                            });
                        } else if (json.contains("atid")) {

                            final RandomFollow randomFollow = gson.fromJson(json, RandomFollow.class);
                            Glide.with(mcontext).load(Path.img(randomFollow.getData().getHead())).into(img);
                            title.setText(randomFollow.getData().getName());
                            price.setText("+" + randomFollow.getData().getMax() + "元");
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add("关注公众号");
                            flow.setAdapter(new TagAdapter<String>(strings) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mcontext).inflate(R.layout.tv,
                                            flow, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            });
                            start.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    Intent intent = new Intent(getActivity(), FollowActivity.class);
                                    intent.putExtra("iv", randomFollow.getData().getHead());
                                    intent.putExtra("title", randomFollow.getData().getName());
                                    intent.putExtra("one", randomFollow.getData().getDan());
                                    intent.putExtra("all", randomFollow.getData().getMax());
                                    intent.putExtra("wechatnum", randomFollow.getData().getWxunid());
                                    intent.putExtra("num", randomFollow.getData().getNum() + "");
                                    intent.putExtra("sum", randomFollow.getData().getSum() + "");
                                    if (randomFollow.getData().getSex().contains("男")) {
                                        intent.putExtra("sex", 1);
                                    } else if (randomFollow.getData().getSex().contains("女")) {
                                        intent.putExtra("sex", 2);
                                    }
                                    startActivity(intent);
                                }
                            });
                        } else if (json.contains("taskid")) {
                            final RandomCard randomCard = gson.fromJson(json, RandomCard.class);
                            Glide.with(mcontext).load(Path.img(randomCard.getData().getLogo())).into(img);
                            title.setText(randomCard.getData().getTitle());
                            price.setText("+" + randomCard.getData().getAcount() + "元");
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add("信用卡秒批");
                            flow.setAdapter(new TagAdapter<String>(strings) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mcontext).inflate(R.layout.tv,
                                            flow, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            });
                            start.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    startActivity(new Intent(getActivity(), CreditCardDetailsActivity.class).putExtra("taskid", randomCard.getData().getTaskid()).putExtra("Detailtype", 4));
                                }
                            });
                        }
                    }
                });


                break;
            default:
                break;
        }
    }

    private int getTotalPoints(AppSummaryObject appSummaryObject) {
        int totalpoints = appSummaryObject.getPoints();
        AppExtraTaskObjectList tempList = appSummaryObject.getExtraTaskList();
        if (tempList != null && tempList.size() > 0) {
            for (int i = 0; i < tempList.size(); ++i) {
                AppExtraTaskObject extraTaskObject = tempList.get(i);
                if (extraTaskObject.getStatus() == AdExtraTaskStatus.NOT_START ||
                        extraTaskObject.getStatus() == AdExtraTaskStatus.IN_PROGRESS) {
                    totalpoints += extraTaskObject.getPoints();
                }
            }
        }
        return totalpoints;
    }

    /**
     * md5 32 小写
     *
     * @param text
     * @return
     */
    public static String encode(String text) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(text.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : result) {
                int number = b & 0xff;
                String hex = Integer.toHexString(number);
                if (hex.length() == 1) {
                    sb.append("0" + hex);
                } else {
                    sb.append(hex);
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    private void getHome() {
        OkHttpDownloadJsonUtil.downloadJson(mcontext, Path.HOME(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    Home home = gson.fromJson(json, Home.class);
                    final List<Share.DataBean> share = home.getShare();
                    lvshare.setAdapter(new ShareAdapter(share, mcontext, 0));
                    lvshare.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(getActivity(), WebActivity.class);
                            intent.putExtra("url", share.get(i).getUrl());
                            intent.putExtra("shid", share.get(i).getShid());
                            intent.putExtra("fen", share.get(i).getFen());
                            intent.putExtra("title", share.get(i).getShname());
                            intent.putExtra("img", share.get(i).getImg());
                            intent.putExtra("type", share.get(i).getType());
                            intent.putExtra("intro", share.get(i).getShcon());
                            intent.putExtra("isshow", share.get(i).getIsshow());
                            intent.putExtra("scon", share.get(i).getShowtext());
                            intent.putExtra("ym", share.get(i).getYuming());
                            getActivity().startActivity(intent);
                        }
                    });
                    final List<Wechat.DataBean> attention = home.getAttention();
                    lvfollow.setAdapter(new FollowAdapter(attention, mcontext));
                    lvfollow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(getActivity(), FollowActivity.class);
                            intent.putExtra("iv", attention.get(i).getHead());
                            intent.putExtra("title", attention.get(i).getName());
                            intent.putExtra("one", attention.get(i).getDan());
                            intent.putExtra("all", attention.get(i).getMax());
                            intent.putExtra("wechatnum", attention.get(i).getWxunid());
                            intent.putExtra("num", attention.get(i).getNum() + "");
                            intent.putExtra("sum", attention.get(i).getSum() + "");
                            if (attention.get(i).getSex().contains("男")) {
                                intent.putExtra("sex", 1);
                            } else if (attention.get(i).getSex().contains("女")) {
                                intent.putExtra("sex", 2);
                            }
                            startActivity(intent);
                        }
                    });
                    final List<Home.BuyBean> buy = home.getBuy();
                    final List<PDD.DataBeanX.DataBean> buyList = new ArrayList<>();
                    for (Home.BuyBean b : buy
                            ) {
                        buyList.add(new PDD.DataBeanX.DataBean(b.getTitle(), b.getImg(), b.getSold_quantity(), b.getMin_group_price(), b.getCoupon_discount(), b.getPromotion_rate()));
                    }
                    lvgw.setAdapter(new PDDAdapter(buyList, mcontext));
                    lvgw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            startActivity(new Intent(mcontext, PDDDetailActivity.class).putExtra("goods_id", buy.get(i).getGoods_id()));
                        }
                    });
                    List<ScreenBean.Data1Bean> card = home.getCard();
                    ArrayList<ScreenBean.DataBean> list = new ArrayList<>();
                    for (ScreenBean.Data1Bean b : card) {
                        list.add(new ScreenBean.DataBean(b.getTaskid(), b.getLogo(), b.getType(), b.getTitle(), b.getAcount(), b.getIsvip(), -1));
                    }
                    ScreenAdapter screenAdapter = new ScreenAdapter(mcontext, list);
                    lvtaskmore.setAdapter(screenAdapter);
                    screenAdapter.setScreenItemListener(new ScreenAdapter.ScreenItemListener() {
                        @Override
                        public void onItemClick(ScreenBean.DataBean item) {
                            if (item.getType() == 4) {
//                    Toast.makeText(mcontext, "信用卡", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getActivity(), CreditCardDetailsActivity.class).putExtra("taskid", item.getTaskid()).putExtra("Detailtype", 4));
                            } else {
                                startActivity(new Intent(getActivity(), CreditTaskDetailsActivity.class).putExtra("taskid", item.getTaskid()));

                            }
                        }
                    });
                } catch (Exception e) {
                    if (mcontext != null) {
                        Toast.makeText(mcontext, "数据异常", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    Context mcontext;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mcontext = activity;
    }

    class GlideImageLoader extends ImageLoader

    {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {

            Glide.with(context).load(path).apply(new RequestOptions().error(R.mipmap.banner_2)).into(imageView);
        }

        @Override
        public ImageView createImageView(Context context) {
            //圆角
            return new RoundAngleImageView(context);
        }
    }
}
